<template>
  <p-select
    :value="value"
    mode="multiple"
    class="select-container"
    placeholder="请输入并选择"
    :filter-option="false"
    :not-found-content="fetching ? undefined : null"
    v-bind="$attrs"
    v-on="$listeners"
    @focus="list = []"
    @search="getUserList"
  >
    <p-spin v-if="fetching" slot="notFoundContent" size="small" />
    <!-- prettier-ignore -->
    <p-select-option 
      v-for="item in list" 
      :key="item[valueKey]"
    >{{ item.empNumber === null ? item.name : item.name + '-' + item.empNumber }}</p-select-option>
  </p-select>
</template>

<script>
import { getOthersHandingList } from '@/api/plan';
import debounce from 'lodash/debounce';
export default {
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    valueKey: {
      type: String,
      default: 'uid',
    },
  },
  data() {
    this.lastFetchId = 0;
    this.getUserList = debounce(this.getUser, 1000);
    return {
      list: [],
      fetching: false,
    };
  },
  methods: {
    handleChange(val) {
      this.$emit('change', val);
    },
    clear() {
      this.list = [];
      this.fetching = false;
    },
    async getUser(keyword) {
      this.lastFetchId += 1;
      const fetchId = this.lastFetchId;
      this.list = [];
      this.fetching = true;
      const res = await getOthersHandingList({
        orgCode: '',
        keyword,
        isDeepSearch: false,
        isSearchNonOrg: false,
        tenantId: 'geek',
        status: 1,
        pageNo: 1,
        limit: 100,
      }).finally(() => {
        this.fetching = false;
      });
      if (fetchId !== this.lastFetchId) {
        return;
      }
      const data = res?.data?.data?.records || [];
      console.log('data: ', data);
      this.list = data
        .filter(item => item.email)
        .map(item => {
          return {
            email: item.email,
            uid: item.uid,
            name: item.name,
            empNumber: item.empNumber,
            handleUser: [item.uid, item.name],
          };
        });
    },
  },
};
</script>
<style lang="less" scoped>
.select-container {
  width: 100%;
}
</style>
